/*
 * @(#)DefaultTemplateExceptionHandler.java $version 2010. 8. 11
 *
 * Copyright 2007-2010 NHN Corp. All rights Reserved. 
 * NHN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */
package com.nhncorp.usf.core.addon.freemarker.exception;

import java.io.Writer;

import org.apache.log4j.Logger;

import freemarker.core.Environment;
import freemarker.template.TemplateException;
import freemarker.template.TemplateExceptionHandler;

/**
 * @author Web Platform Development Team
 */
public class DefaultTemplateExceptionHandler implements TemplateExceptionHandler {
    private Logger log = Logger.getLogger(DefaultTemplateExceptionHandler.class);

    /**
     * @param ex  TemplateException
     * @param env Environment
     * @param out Writer
     * @throws TemplateException the TemplateException
     */
    public void handleTemplateException(TemplateException ex, Environment env, Writer out) throws TemplateException {
        boolean ignore = false;
        String message = ex.getMessage();
        ignore = isAttemptException(ex);

        if (!ignore) {
            //			System.out.println(ex.getMessage());
            log.error(message);
        } else {
            throw ex;
        }
    }

    /**
     * Checks if is attempt exception.
     *
     * @param ex the e
     * @return true, if is attempt exception
     */
    private boolean isAttemptException(TemplateException ex) {
        StackTraceElement[] stList = ex.getStackTrace();

        for (int i = 0; i < stList.length; i++) {
            if (stList[i].toString().startsWith("freemarker.core.AttemptBlock")) {
                return true;
            }
        }

        return false;
    }
}
